const app = getApp();
var that;
var util = require('../../utils/util.js');
var today = util.formatDay(new Date());
var day;
var UserArray = [];
var fromId = "";
Page({
  data: {
    img1: '/pages/img/image_sending.png',
    img2: '/pages/img/image_complete.png',
    hidden: '',
    date: util.formatDay(new Date()),
    id: "",
    code: "",
    stall: "",
    trackState: "",
    time: "08:00",
    carName: "",
    driverName: "",
    driverId: "",
    Users: [],
    UserIndex: 0,
    sea_name: "",
    sea_code: "",
    file: ""
  },
  //监听输入的客户名称
  nameInp: function (e) {
    this.data.sea_name = e.detail.value;
  },
  //监听输入的客户单号
  codeInp: function (e) {
    this.data.sea_code = e.detail.value;
  },
  onLoad: function (options) {
    that = this;
    day = options.day;
    if (day != null) {
      today = day;
    } else if (getApp().day != null) {
      today = getApp().day;
    }
    search();
    var title = "业务";
    wx.setNavigationBarTitle({
      title: title
    });
  },
  bindUserChange: function (e) {
    this.setData({
      UserIndex: e.detail.value,
      driverName: UserArray[e.detail.value].name,
      driverId: UserArray[e.detail.value].id,
      carName: UserArray[e.detail.value].carName,
    })
  },
  // 关闭提货图片弹窗
  closeDialog: function () {
    this.setData({
      istrue: false
    })
  },
  // 打开提货图片弹窗
  openDialog: function (e) {
    console.log(e.target.id)
    this.setData({
      istrue: true,
      fromId: e.target.id
    })
  },
  // 使点击的按钮高亮
  btnclick: function (e) {
    wx.navigateTo({
      url: "/pages/orders_detail/orders_detail?id=" + e.target.id
    });
  },
  // 保存并关闭弹窗
  saveDialog: function (e) {
    // 弹窗填写提货时间
    console.log(e.target.id);
    var obj = {
      "id": "",
      "companyId": getApp().userInfo.companyId,
      "fromId": that.data.fromId,
      "path": that.data.file,
      "thumbnail":that.data.file,
    };
    wx.request({
      url: app.serverIP + '/kkl/cms/app/fileInfo/add?token=' + app.token,
      method: "POST",
      data: JSON.stringify(obj),
      contentType: "application/json",
      success: function (res) {
        if (res.data.code == "200") {
          wx.showToast({
            title: "操作成功\n",
            icon: 'none', //如果要纯文本，不要icon，将值设为'none'
            duration: 2000
          })
          search();
        } else {
          wx.showToast({
            title: "修改失败:" + res.data.code,
            icon: 'none', //如果要纯文本，不要icon，将值设为'none'
            duration: 2000
          })
          console.log(res.data.message)
        }
      },
    })
    this.setData({
      istrue: false
    })
  },
  chooseImage: function (e) {
    wx.chooseMedia({
      sizeType: ['original', 'compressed'], // 图片自动压缩
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      mediaType: ['image'],
      count: 1,
      success: function (res) {
        // 上传前对图片进行压缩
        wx.compressImage({
          src: res.tempFiles[0].tempFilePath, // 图片路径
          quality: 50, // 压缩质量
          success: function (res) {
            console.log(res.tempFilePath)
            wx.uploadFile({
              url: app.imgIP + "/kkl/upload/fileUpload?folderName=img", //请求地址
              data: "",
              filePath: res.tempFilePath,
              name: "file",
              header: {
                "Content-Type": "multipart/form-data"
              },
              formData: {
                "user": "test",
              },
              success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var imgdata = JSON.parse(res.data);
                that.setData({
                  files: app.imgIP + imgdata.data.image,
                  file: imgdata.data.image
                })
              }
            })
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  //检测下拉刷新事件
  onPullDownRefresh: function () {
    if (day != null) {
      today = day;
    } else if (getApp().day != null) {
      today = getApp().day;
    }
    // console.log("检测下拉刷新事件")
    // console.log(today)
    search();
    wx.stopPullDownRefresh();
  },
  searchQuery: function () {
    search();
  }
})

// 获取订单
function search() {
  if (!isLogin()) {
    wx.showToast({
      title: "请先登录系统才能查看自己的订单!",
      icon: 'none', //如果要纯文本，不要icon，将值设为'none'
      duration: 2000
    })
    return;
  }
  if (!isUserType()) {
    wx.showToast({
      title: "请先录入您的身份信息,进入我的页面点击点击个人资料录入姓名身份后才可接单!",
      icon: 'none', //如果要纯文本，不要icon，将值设为'none'
      duration: 2000
    })
    return;
  }

  // 验证查询条件
  var otherSearchStr = "";
  if (that.data.sea_name != "") {
    otherSearchStr = otherSearchStr + "&customerName=" + that.data.sea_name;
  }
  if (that.data.sea_code != "") {
    otherSearchStr = otherSearchStr + "&orderCode=" + that.data.sea_code;
  }

  otherSearchStr = otherSearchStr + '&beginOrderTime=' + today + " 00:00:00";
  console.log(app.serverIP + '/kkl/cms/app/OrdersCarrier/list?token=' + app.token + otherSearchStr)
  wx.request({
    url: app.serverIP + '/kkl/cms/app/OrdersCarrier/list?token=' + app.token + otherSearchStr,
    dataType: "json",
    success: function (res) {
      if (res.data.code == "200") {}
      binding(res.data.data)
    },
  })
}

function binding(data) {
  const orders = [];
  console.log(data);
  for (var i in data) {
    data[i].orderTime = initTime(data[i].orderTime);
    if (data[i].upTime != null && data[i].upTime != '') {
      data[i].upTime = initTime(data[i].upTime);
    }
    if (data[i].downTime != null && data[i].downTime != '') {
      data[i].downTime = initTime(data[i].downTime);
    }
    orders.push(data[i]);
  }
  wx.getSystemInfo({
    success: function (res) {
      that.setData({
        array: orders,
      })
    }
  })
}

function initTime(time) {
  return time.substring(5, 16);;
}

function isLogin() {
  if (app.userInfo != null) {
    return true;
  } else {
    console.log("用户还没有登录");
    return false;
  }
}

function isUserType() {
  if (app.userInfo.carNum == null || app.userInfo.carNum == "") {
    return false;
  } else {
    return true;
  }
}